/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.ext.rs.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.commons.io.IOUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class JsonUtil {

    org.slf4j.Logger log = LoggerFactory.getLogger(JsonUtil.class);


    public Document convert(InputStream in) throws TransformerException {
        try {
            JSONObject jo = new JSONObject(IOUtils.toString(in));
            return convert(jo);
        } catch (JSONException e) {
            throw new TransformerException(e);
        } catch (IOException e) {
            throw new TransformerException(e);
        }
    }


    private void convert(JSONArray srcArr, String arrName, Element targetElement)
            throws JSONException {
        int len = srcArr.length();
        for (int i = 0; i < len; i++) {
            Element arrElement = targetElement.getOwnerDocument()
                    .createElement(arrName);
            targetElement.appendChild(arrElement);
            Object item = srcArr.get(i);

            if (item == null) {
                targetElement.appendChild(arrElement);
            } else if (item instanceof JSONArray) {
                convert((JSONArray) item, arrName, arrElement);
            } else if (item instanceof JSONObject) {
                convert((JSONObject) item, arrElement);
            }

            else {
                arrElement.appendChild(targetElement.getOwnerDocument()
                        .createTextNode(item.toString()));
            }

        }
    }


    public Document convert(JSONObject obj) throws TransformerException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            Document d = dbf.newDocumentBuilder().newDocument();

            Element parent = d.createElement("root");
            d.appendChild(parent);
            convert(obj, parent);
            return d;

        } catch (ParserConfigurationException e) {
            throw new TransformerException(e);
        } catch (JSONException e) {
            throw new TransformerException(e);
        }
    }


    @SuppressWarnings("unchecked")
    private void convert(JSONObject srcObj, Element targetElement)
            throws JSONException {
        Iterator<String> t = srcObj.keys();

        while (t.hasNext()) {
            String key = (String) t.next();

            Element entryElement = targetElement.getOwnerDocument()
                    .createElement(key);

            Object obj = srcObj.get(key);
            if (srcObj.isNull(key)) {
                targetElement.appendChild(entryElement);
            }

            else if (obj instanceof JSONArray) {
                // targetElement.appendChild(entryElement);
                JSONArray arr = (JSONArray) obj;
                convert(arr, key, targetElement);
            } else if (obj instanceof JSONObject) {
                targetElement.appendChild(entryElement);
                JSONObject jobj = (JSONObject) obj;
                convert(jobj, entryElement);
            }

            else {
                targetElement.appendChild(entryElement);
                Node tn = entryElement.getOwnerDocument().createTextNode(
                        obj.toString());
                entryElement.appendChild(tn);
                targetElement.appendChild(entryElement);
            }

        }

    }


    public Document convert(String json) throws TransformerException {
        try {
            JSONObject jo = new JSONObject(json);
            return convert(jo);
        } catch (JSONException e) {
            throw new TransformerException(e);
        }
    }


    public void testx() {

    }
}
